package com.chexiehui.jc.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusLinearLayout;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BrandInfo;
import com.chexiehui.jc.entity.BrandListInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.HomeActionInfo;
import com.chexiehui.jc.event.GlobalFollowSeriesEvent;
import com.chexiehui.jc.mvp.car.CarGarageNewCovenant;
import com.chexiehui.jc.mvp.car.CarGarageNewPresenter;
import com.chexiehui.jc.ui.activity.CarBrandSaleListActivity;
import com.chexiehui.jc.ui.activity.CarSeriesDetailsActivity;
import com.chexiehui.jc.ui.activity.ChooseCarModelActivity;
import com.chexiehui.jc.ui.activity.ConditionalCarSelectionActivity;
import com.chexiehui.jc.ui.activity.HotRankingListActivity;
import com.chexiehui.jc.ui.activity.NewCarListActivity;
import com.chexiehui.jc.ui.activity.SalesRankingListActivity;
import com.chexiehui.jc.ui.activity.SearchActivity;
import com.chexiehui.jc.ui.activity.SpecialCarListActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.chexiehui.jc.widget.indexbar.IndexBar;
import com.chexiehui.jc.widget.indexbar.suspension.SuspensionDecoration;
import com.nex3z.flowlayout.FlowLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 新车
 */

public class CarGarageNewFragment extends BaseMvpLazyLoadFragment<CarGarageNewPresenter> implements CarGarageNewCovenant.View {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_head_search)
    RadiusLinearLayout llHeadSearch;
    @BindView(R.id.nsgv_head_action)
    NonSlidingGridView nsgvHeadAction;
    @BindView(R.id.nsgv_head_follow_car)
    NonSlidingGridView nsgvHeadFollowCar;
    @BindView(R.id.nsgv_head_crux_car)
    NonSlidingGridView nsgvHeadCruxCar;
    @BindView(R.id.fl_follow_tip)
    FlowLayout flFollowTip;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.ib_right_index_bar)
    IndexBar ibRightIndexBar;
    @BindView(R.id.tv_side_bar_hint)
    TextView tvSideBarHint;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private CommonAdapter<CarSeriesInfo> followCarAdapter;
    private List<CarSeriesInfo> followCarList;
    private CommonAdapter<CarSeriesInfo> cruxCarAdapter;
    private List<CarSeriesInfo> cruxCarList;
    private com.zhy.adapter.recyclerview.CommonAdapter<BrandInfo> carBrandAdapter;
    private List<BrandInfo> brandListData;
    private SuspensionDecoration suspensionDecoration;

    public static CarGarageNewFragment getInstance() {
        CarGarageNewFragment fragment = new CarGarageNewFragment();
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_garage_new;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDragRate(0.5f);
        loadingLayout.setStatus(LoadingLayout.Loading);
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getFollowCarList();
            mvpPresenter.getCruxCarList();
            mvpPresenter.getCraGradeList();
            mvpPresenter.getBrandList();
        });
        List<HomeActionInfo> actionList = new ArrayList<>();
        actionList.add(new HomeActionInfo("条件选车", R.mipmap.ic_car_tjxc));
        actionList.add(new HomeActionInfo("销量排行", R.mipmap.ic_car_xlph));
        actionList.add(new HomeActionInfo("新车发布", R.mipmap.ic_car_xcsf));
        actionList.add(new HomeActionInfo("热门排行", R.mipmap.ic_car_rxph));
        actionList.add(new HomeActionInfo("特价车", R.mipmap.ic_car_tjc));
        nsgvHeadAction.setAdapter(new CommonAdapter<HomeActionInfo>(mActivity, R.layout.item_car_garage_new_action, actionList) {
            @Override
            protected void convert(ViewHolder viewHolder, HomeActionInfo item, int position) {
                viewHolder.setText(R.id.tv_item_label, item.getName());
                viewHolder.setImageResource(R.id.iv_item_icon, item.getIcon());
            }
        });
        nsgvHeadAction.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivityByFlag(position);
        });

        followCarList = new ArrayList<>();
        followCarList.add(new CarSeriesInfo(true));
        nsgvHeadFollowCar.setAdapter(followCarAdapter = new CommonAdapter<CarSeriesInfo>(mActivity, R.layout.item_car_garage_follow_car, followCarList) {
            @Override
            protected void convert(ViewHolder viewHolder, CarSeriesInfo item, int position) {
                if (item.isAddCarFollow()) {
                    viewHolder.getView(R.id.iv_item_add_icon).setVisibility(View.VISIBLE);
                    viewHolder.setText(R.id.tv_item_label, "添加车系");
                    viewHolder.setImageResource(R.id.iv_item_icon, R.mipmap.ic_car_follow_add);
                } else {
                    viewHolder.getView(R.id.iv_item_add_icon).setVisibility(View.GONE);
                    GlideUtil.loadImageViewCrop(mContext, item.getImg(), viewHolder.getView(R.id.iv_item_icon),
                            R.drawable.shape_square, R.drawable.shape_square);
                    viewHolder.setText(R.id.tv_item_label, item.getName());
                }
            }
        });
        nsgvHeadFollowCar.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            if (followCarList.get(position).isAddCarFollow()) {
                Intent intent = new Intent(getActivity(), ChooseCarModelActivity.class);
                intent.putExtras(new BundleBuilder().putInt("chooseLevel", 2).create());
                startActivityForResult(intent, 21);
            } else {
                startActivity(CarSeriesDetailsActivity.class,
                        new BundleBuilder().putString("seriesId", followCarList.get(position).getId())
                                .create());
            }
        });

        cruxCarList = new ArrayList<>();
        cruxCarList.add(new CarSeriesInfo(true));
        nsgvHeadCruxCar.setAdapter(cruxCarAdapter = new CommonAdapter<CarSeriesInfo>(mActivity, R.layout.item_car_garage_crux_car, cruxCarList) {
            @Override
            protected void convert(ViewHolder viewHolder, CarSeriesInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), viewHolder.getView(R.id.iv_item_icon),
                        R.drawable.shape_square, R.drawable.shape_square);
                viewHolder.setText(R.id.tv_item_label, item.getName());
            }
        });
        nsgvHeadCruxCar.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivity(CarSeriesDetailsActivity.class,
                    new BundleBuilder().putString("seriesId", cruxCarList.get(position).getId())
                            .create());
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        recycler.setLayoutManager(layoutManager);
        brandListData = new ArrayList<>();
        carBrandAdapter = new com.zhy.adapter.recyclerview.CommonAdapter<BrandInfo>(mActivity, R.layout.item_car_garage_new_brand, brandListData) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, BrandInfo brandInfo, int position) {
                holder.setText(R.id.tv_item_name, brandInfo.getName());
                Glide.with(mActivity)
                        .load(brandInfo.getImg())
                        .into((ImageView) holder.getView(R.id.iv_item_icon));
            }
        };
        carBrandAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarBrandSaleListActivity.class,
                        new BundleBuilder()
                                .putSerializable("entity", brandListData.get(position))
                                .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(carBrandAdapter);
        suspensionDecoration = new SuspensionDecoration(mActivity, brandListData);
        recycler.addItemDecoration(suspensionDecoration);
        //indexbar初始化
        ibRightIndexBar.setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                .setNeedRealIndex(false)//设置需要真实的索引
                .setSourceDatasAlreadySorted(true)
                .setmLayoutManager(layoutManager);//设置RecyclerView的LayoutManager
        isPrepared = true;
        lazyLoad();
    }

    @OnClick({R.id.ll_head_search})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.ll_head_search:
                startActivity(SearchActivity.class);
                break;
        }
    }

    private void startActivityByFlag(int flag) {
        switch (flag) {
            case 0:
                startActivity(ConditionalCarSelectionActivity.class);
                break;
            case 1:
                startActivity(SalesRankingListActivity.class);
                break;
            case 2:
                startActivity(NewCarListActivity.class);
                break;
            case 3:
                startActivity(HotRankingListActivity.class);
                break;
            case 4:
                startActivity(SpecialCarListActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getFollowCarList();
        mvpPresenter.getCruxCarList();
        mvpPresenter.getCraGradeList();
        mvpPresenter.getBrandList();
    }

    @Override
    protected CarGarageNewPresenter createPresenter() {
        return new CarGarageNewPresenter(this);
    }

    @Override
    public void onGetFollowCarListSuccess(BaseModel<BasePage<CarSeriesInfo>> successResult) {
        followCarList.clear();
        followCarList.addAll(successResult.getData().getItems());
        followCarList.add(new CarSeriesInfo(true));
        followCarAdapter.notifyDataSetChanged();
        nsgvHeadFollowCar.setNumColumns(followCarList.size());
        nsgvHeadFollowCar.setColumnWidth(SizeUtils.dp2px(80));
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvHeadFollowCar.getLayoutParams();
        lp.width = SizeUtils.dp2px(80) * followCarList.size() + SizeUtils.dp2px(5) * (followCarList.size() - 1);
        nsgvHeadFollowCar.setLayoutParams(lp);
    }

    @Override
    public void onGetFollowCarListFailure(BaseModel<Object> failureResult) {
        followCarList.clear();
        followCarList.add(new CarSeriesInfo(true));
        followCarAdapter.notifyDataSetChanged();
        nsgvHeadFollowCar.setNumColumns(followCarList.size());
        nsgvHeadFollowCar.setColumnWidth(SizeUtils.dp2px(80));
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvHeadFollowCar.getLayoutParams();
        lp.width = SizeUtils.dp2px(80) * followCarList.size() + SizeUtils.dp2px(5) * (followCarList.size() - 1);
        nsgvHeadFollowCar.setLayoutParams(lp);
    }

    @Override
    public void onGetCruxCarListSuccess(BaseModel<BasePage<CarSeriesInfo>> successResult) {
        cruxCarList.clear();
        cruxCarList.addAll(successResult.getData().getItems());
        cruxCarAdapter.notifyDataSetChanged();
        nsgvHeadCruxCar.setNumColumns(cruxCarList.size());
        nsgvHeadCruxCar.setColumnWidth(SizeUtils.dp2px(109));
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvHeadCruxCar.getLayoutParams();
        lp.width = SizeUtils.dp2px(109) * cruxCarList.size() + SizeUtils.dp2px(5) * (cruxCarList.size() - 1);
        nsgvHeadCruxCar.setLayoutParams(lp);
    }

    @Override
    public void onGetCruxCarListFailure(BaseModel<Object> failureResult) {
        cruxCarList.clear();
        cruxCarAdapter.notifyDataSetChanged();
        nsgvHeadCruxCar.setVisibility(View.GONE);
    }

    @Override
    public void onGetCraGradeListSuccess(BaseModel<List<DictInfo>> successResult) {
        flFollowTip.removeAllViews();
        for (int i = 0; i < successResult.getData().size(); i++) {
            RadiusTextView radiusTextView = (RadiusTextView) View.inflate(mActivity, R.layout.item_only_car_type2, null);
            radiusTextView.setTag(successResult.getData().get(i));
            radiusTextView.setText(successResult.getData().get(i).getValue());
            radiusTextView.setOnClickListener(noDoubleClickListener);
            //radiusTextView.setSelected(carTypePosition == i);
            flFollowTip.addView(radiusTextView);
        }
    }

    private NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View view) {
            if(view.getTag() != null){
                startActivity(ConditionalCarSelectionActivity.class, new BundleBuilder().putSerializable("gradeInfo", (DictInfo)view.getTag()).create());
            }
        }
    };

    @Override
    public void onGetCraGradeListFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public void onGetBrandListSuccess(BaseModel<List<BrandListInfo>> successResult) {
        mHasLoadedOnce = true;
        if (loadingLayout.getStatus() == LoadingLayout.Loading) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        ibRightIndexBar.setVisibility(View.VISIBLE);
        List<BrandInfo> list = new ArrayList<>();
        for (int i = 0; i < successResult.getData().size(); i++) {
            for (int j = 0; j < successResult.getData().get(i).getBrands().size(); j++) {
                successResult.getData().get(i).getBrands().get(j).setSpell(successResult.getData().get(i).getSpell());
            }
            list.addAll(successResult.getData().get(i).getBrands());
        }
        brandListData.clear();
        brandListData.addAll(list);
        carBrandAdapter.notifyDataSetChanged();
        ibRightIndexBar.setmSourceDatas(brandListData)//设置数据
                .invalidate();
        suspensionDecoration.setmDatas(brandListData);
    }

    @Override
    public void onGetBrandListFailure(BaseModel<Object> failureResult) {
        if (loadingLayout.getStatus() == LoadingLayout.Loading) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        ibRightIndexBar.setVisibility(View.GONE);
        brandListData.clear();
        carBrandAdapter.notifyDataSetChanged();
        ibRightIndexBar.setmSourceDatas(brandListData)//设置数据
                .invalidate();
        suspensionDecoration.setmDatas(brandListData);
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(false);
        }
    }

    @Override
    public void onDoFollowSeriesSuccess(BaseModel<String> successResult) {
        EventBus.getDefault().post(new GlobalFollowSeriesEvent(successResult.getData(), true));
    }

    @Override
    public void onDoFollowSeriesFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 21:
                if (resultCode == -1) {
                    if (data != null) {
                        CarSeriesInfo seriesInfo = (CarSeriesInfo) data.getSerializableExtra("seriesInfo");
                        if (seriesInfo != null) {
                            mvpPresenter.doFollowSeries(seriesInfo.getId());
                        }
                    }
                }
                break;
        }
    }

    @Subscribe
    public void onGlobalFollowSeriesEvent(GlobalFollowSeriesEvent event){
        mvpPresenter.getFollowCarList();
    }
}
